package com.example.k12.view

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView

class CircularImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val paint: Paint = Paint().apply {
        isAntiAlias = true
    }

    private var radius = 0.0f

    override fun onDraw(canvas: Canvas) {
        val drawable = drawable ?: return

        if (width == 0 || height == 0) {
            super.onDraw(canvas)
            return
        }

        if (drawable is BitmapDrawable) {
            val bitmap = drawable.bitmap
            if (bitmap != null && !bitmap.isRecycled) {
                val circleBitmap = getCircularBitmap(bitmap)
                canvas.drawBitmap(circleBitmap, 0f, 0f, paint)
            }
        } else {
            super.onDraw(canvas)
        }
    }

    private fun getCircularBitmap(bitmap: Bitmap): Bitmap {
        val size = minOf(width, height)
        if (size <= 0) return bitmap

        val output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)

        val paint = Paint().apply {
            isAntiAlias = true
            isFilterBitmap = true
            isDither = true
        }

        // 计算圆形的半径
        radius = size / 2.0f

        // 绘制圆形背景
        canvas.drawCircle(radius, radius, radius, paint)

        // 使用SRC_IN模式进行裁剪
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

        // 计算源图像的绘制位置，使其居中
        val left = (size - bitmap.width) / 2f
        val top = (size - bitmap.height) / 2f
        canvas.drawBitmap(bitmap, left, top, paint)

        paint.xfermode = null

        return output
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        // 确保是正方形
        val width = measuredWidth
        val height = measuredHeight
        val size = minOf(width, height)
        setMeasuredDimension(size, size)
    }
}
